/* 
file：用户
*/
const {User} = require('../model')
const {jwtSecret} = require('../config/config.default')
const jwt = require('../util/jwt')


exports.login = async (req,res,next)=>{
    const user = await User.findOne({email:req.body.email}).select(['password','email','username'])
    if(!user){
        return res.status(400).json('账户不存在')
    }
    console.log('user',user);
    if(user.password !== req.body.password){
        return res.status(400).end('账户与密码不匹配')
    }
    const token = await jwt.sign({
        userid:user._id,
    },jwtSecret,{
        expiresIn:60*60*24
    })
    delete user.password
    res.status(200).json({
        ...user.toJSON(),
        token
    })
}


// 创建
exports.register = async (req,res,next)=>{
    const dbres = await User.findOne({email:req.body.email})
    if(dbres) return res.status(200).end('用户已存在')
    const user = new User(req.body)
    await user.save()
    res.status(200).json({
        user
    })
}

// 获取
exports.getCurrentUser = async (req,res,next)=>{
    const user = await User.findOne({email:req.query.email})
    if(!user) return res.status(200).end('用户不存在')
    res.status(200).json({user})
}

// 获取所有用户
exports.getAllUser = async (req,res,next)=>{
    const allUser = await User.find()
    res.status(200).json({
        users:allUser
    })
}

// 更新
exports.updateCurrentUser = async (req,res,next)=>{
    const user = await User.updateOne({username:req.body.username},{username:req.body.newname,updateAt:Date.now()})
    res.status(200).json('更新成功')
}

// 删除
exports.deleteUser = async (req,res,next)=>{
    const user = await User.findOne({email:req.body.email})
    if(!user) return res.status(200).end('用户不存在')
    await user.remove()
    res.status(200).json({
        user
    })
}